using Send2Sharepoint.Common;
using Microsoft.Office.Interop.Outlook;
using System.ComponentModel;
using Exception = System.Exception;

namespace Send2Sharepoint.Outlook
{
    class UploadOutlookFolder : WorkItem
    {
        public MAPIFolder SuccessFolder { get; set; }
        public MAPIFolder FailedFolder { get; set; }
        public MAPIFolder Folder { get; set; }

        #region IWorkItem Members

        public UploadOutlookFolder(MAPIFolder folder, MAPIFolder successFolder, MAPIFolder failedFolder)
        {
            Folder = folder;
            SuccessFolder = successFolder;
            FailedFolder = failedFolder;
        }
        
        internal override void Upload(BackgroundWorker worker, DoWorkEventArgs e)
        {
            try
            {
                var outlookItems = Folder.Items;
                var totalItems = outlookItems.Count;
                var count = 1;
                var lastPercentDone = 0;
                GenericOutlookItem genericOutlookitem;

                while (outlookItems.Count > 0)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    var oItem = outlookItems[1];
                    genericOutlookitem = new GenericOutlookItem(oItem);
                    try
                    {
                        genericOutlookitem.Upload(IndexInformation);
                        genericOutlookitem.Move(SuccessFolder);
                    }
                    catch
                    {
                        genericOutlookitem.Move(FailedFolder);
                    }
                    genericOutlookitem.Dispose();
                    var percentDone = count / totalItems * 100;
                    if (percentDone > lastPercentDone)
                    {
                        worker.ReportProgress(percentDone);
                        lastPercentDone = percentDone;
                    }
                    count++;
                    outlookItems = Folder.Items;
                }
            }
            catch (Exception ex)
            {
                Logging.WriteException(ex);
                throw;
            }
        }
        #endregion
    }
}
